<template>
  <div class="hospitalPosition">
    <el-form ref="hospitalSelfLocation" :model="hospitalSelfLocation" :rules="rules">
      <el-form-item label="医院自提位置" required>
        <el-col :span="21">
          <el-col :span="24" style="margin-bottom: 30px;">
            <el-col :span="8">
              <el-form-item prop="locationName">
                <el-input v-model="hospitalSelfLocation.locationName" placeholder="输入自提位置名称" style="width:250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业时间">
                <el-row type="flex" justify="around">
                  <el-time-select
                    v-model="hospitalSelfLocation.startHour"
                    placeholder="开始时间"
                    :picker-options="{
                      start: '06:00',
                      end: '24:00',
                      maxTime:hospitalSelfLocation.endHour
                    }"
                    value-format="HH:mm"
                    format="HH:mm"
                  />
                  <span>——</span>
                  <el-time-select
                    v-model="hospitalSelfLocation.endHour"
                    placeholder="结束时间"
                    :picker-options="{
                      start: '06:00',
                      end: '24:00',
                      minTime:hospitalSelfLocation.startHour
                    }"
                    value-format="HH:mm"
                    format="HH:mm"
                  />
                </el-row>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24" style="margin-bottom: 30px;">
            <el-form-item label="位置备注">
              <el-input v-model="hospitalSelfLocation.remark" placeholder="输入位置内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-bottom: 30px;">
            <el-form-item label="位置图示">
              <el-upload
                :action="uploadPath"
                list-type="picture-card"
                accept=".jpg,.png"
                class="ele-col-upload"
                :data="{path:path,fileType: 8}"
                :before-upload="beforeAvatarUpload"
                :on-success="uploadCommodityUrl"
                :limit="limitCount"
                :on-change="isOverLimit"
                :on-remove="onRemove"
                :class="{hide:hideUpload}"
                :file-list="hospitalSelfLocation.imgs"
              >
                <i class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-bottom: 30px;">
            <el-form-item label="归位桩:" prop="hpFlag">
              <el-radio-group v-model="hospitalSelfLocation.hpFlag" @change="changeHpFlag">
                <el-radio label="1">有归位桩</el-radio>
                <el-radio label="0">无归位桩</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-bottom: 30px;">
            <el-form-item label="库存:" prop="inventoryFlag">
              <el-radio-group v-model="hospitalSelfLocation.inventoryFlag" disabled>
                <el-radio label="0">医院库存</el-radio>
                <el-radio label="1">门店库存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-bottom: 30px;">
            <el-form-item label="是否免费:" prop="isFree">
              <el-radio-group v-model="hospitalSelfLocation.freeFlag">
                <el-radio label="0">免费</el-radio>
                <el-radio label="1">不免费</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="hospitalSelfLocation.hpFlag =='0'" :span="24" style="margin-bottom: 30px;">
            <el-form-item label="库存管理员:" required>
              <el-col :span="20">
                <el-col v-for="(item,index) in stockManagerList" :key="index" :span="20">
                  <hospital-stock-manager ref="hospitalPhone" :phone="item" :index="index" @delStockManager="delStockManager" />
                </el-col>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="20">
                <el-col :span="20">
                  <el-button type="text" @click="addStockManager">添加</el-button>
                </el-col>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col v-if="hospitalSelfLocation.inventoryFlag =='0' " :span="24" style="margin-bottom: 30px;">
            <el-form-item label="医院库存:" required>
              <el-col :span="20">
                <el-col :span="24">
                  <hospital-stock-table ref="hospitalGoodsList" />
                </el-col>
              </el-col>
            </el-form-item>
          </el-col>
        </el-col>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
import { uploadPath } from '@/api/upload'
import HospitalStockManager from '@/components/HospitalStockManager'
import HospitalStockTable from '@/components/HospitalStockTable'
import { getHospitalStoreGoodsMessage } from '@/api/customAPI/shop/hospitalManage'

export default {
  name: 'HospitalPosition',
  components: { HospitalStockManager, HospitalStockTable },
  props: {
    index: {
      type: Number,
      required: true
    },
    selfPositionList: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      uploadPath,
      path: '/image',
      limitCount: 1,
      hideUpload: false,
      changeData: true,
      /** 仓库管理员联系方式列表*/
      stockManagerList: [''],
      hospitalSelfLocation: {
        id: null,
        locationName: null,
        startHour: null,
        endHour: null,
        remark: null,
        imgs: [],
        hpFlag: '0',
        inventoryFlag: '0',
        freeFlag: '0',
        adminPhone: '',
        hospitalSelfLocationEquList: []
      },
      rules: {
        hpFlag: [
          { required: true, message: '请选择是否有归为桩', trigger: 'blur' }
        ],
        inventoryFlag: [
          { required: true, message: '请选择库存', trigger: 'blur' }
        ],
        locationName: [
          { required: true, message: '请输入医院自提位置', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    setData(item) {
      if (item) {
        this.hospitalSelfLocation.id = item.id
        this.hospitalSelfLocation.locationName = item.locationName
        if (item.startHour) {
          this.hospitalSelfLocation.startHour = item.startHour
        }
        if (item.endHour) {
          this.hospitalSelfLocation.endHour = item.endHour
        }
        if (item.remark) {
          this.hospitalSelfLocation.remark = item.remark
        }
        if (item.imgs && item.imgs.length > 0) {
          this.hospitalSelfLocation.imgs = item.imgs.split(',').map((item, index) => {
            return {
              name: 'image' + index,
              url: this.$parseImgUrl(item),
              imgUrl: item
            }
          })
          this.hideUpload = this.hospitalSelfLocation.imgs.length >= this.limitCount
        }
        this.hospitalSelfLocation.hpFlag = item.hpFlag.toString()
        this.hospitalSelfLocation.inventoryFlag = item.inventoryFlag.toString()
        this.hospitalSelfLocation.freeFlag = item.freeFlag.toString()
        if (this.hospitalSelfLocation.hpFlag == '0') {
          this.hospitalSelfLocation.adminPhone = item.adminPhone
          this.stockManagerList = item.adminPhone.split(',')
        }
        if (this.hospitalSelfLocation.inventoryFlag == '0') {
          this.getHospitalStoreGoods(item)
        }
      }
    },

    // 图片大小限制
    beforeAvatarUpload: function(file) {
      const isImg = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isSize = file.size / 1024 / 1024 < 2

      if (!isImg) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isSize) {
        this.$message.error('上传图片大小不能超过2MB!')
      }
      return isImg && isSize
    },
    uploadCommodityUrl(res, file) {
      file.imgUrl = res.data.relativePath
      this.hospitalSelfLocation.imgs.push(file)
    },
    /** 超出上传数量隐藏上传按钮*/
    isOverLimit(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
    },
    onRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount
      const index = this.$XEUtils.findIndexOf(this.hospitalSelfLocation.imgs, item => item.uid === file.uid)
      if (index >= 0) {
        this.hospitalSelfLocation.imgs.splice(index, 1)
      }
    },
    delStockManager(index) {
      console.log(index)
      this.stockManagerList.splice(index, 1)
    },
    addStockManager() {
      this.stockManagerList.push('')
    },
    changeHpFlag() {
      if (this.hospitalSelfLocation.hpFlag == '0') {
        this.hospitalSelfLocation.inventoryFlag = '0'
        this.getHospitalStoreGoods({ hospitalSelfLocationEquList: [] })
      } else if (this.hospitalSelfLocation.hpFlag == '1') {
        this.hospitalSelfLocation.inventoryFlag = '1'
      }
    },
    getHospitalStoreGoods(item) {
      getHospitalStoreGoodsMessage(this.selfPositionList).then(res => {
        console.log(res.data)
        const list = res.data.data
        this.hospitalSelfLocation.hospitalSelfLocationEquList = []
        if (item.hospitalSelfLocationEquList.length > 0) {
          list.forEach(inf => {
            item.hospitalSelfLocationEquList.forEach(info => {
              if (inf.storeId == info.storeId && inf.goodsId == info.goodsId && inf.skuId == info.skuId) {
                this.hospitalSelfLocation.hospitalSelfLocationEquList.push({
                  storeId: inf.storeId,
                  storeName: inf.storeName,
                  goodsId: inf.goodsId,
                  goodsName: inf.goodsName,
                  storeGoodsId: inf.storeGoodsId,
                  skuId: inf.skuId,
                  skuName: inf.skuName,
                  equIdArray: info.equIdArray
                })
              }
            })
          })
        } else if (item.hospitalSelfLocationEquList.length == 0) {
          list.forEach(inf => {
            this.hospitalSelfLocation.hospitalSelfLocationEquList.push({
              storeId: inf.storeId,
              storeName: inf.storeName,
              goodsId: inf.goodsId,
              goodsName: inf.goodsName,
              storeGoodsId: inf.storeGoodsId,
              skuId: inf.skuId,
              skuName: inf.skuName,
              equIdArray: ''
            })
          })
        }

        console.log(this.hospitalSelfLocation.hospitalSelfLocationEquList)
        this.$nextTick(() => {
          this.$refs.hospitalGoodsList.setData(this.hospitalSelfLocation.hospitalSelfLocationEquList)
        })
      })
    },
    getData() {
      const data = this.$XEUtils.clone(this.hospitalSelfLocation, true)
      if (!this.hospitalSelfLocation.locationName) {
        this.$message.error('医院自提位置不能为空')
        return
      }
      if (this.hospitalSelfLocation.inventoryFlag == '0') {
        this.hospitalSelfLocation.hospitalSelfLocationEquList = this.$refs.hospitalGoodsList.getData()
      }
      if (this.hospitalSelfLocation.hospitalSelfLocationEquList.length == 0 && this.hospitalSelfLocation.inventoryFlag == '0') {
        this.$message.error('医院库存列表不能为空')
        return
      }
      const hospitalPhoneList = []
      if (this.hospitalSelfLocation.hpFlag == '0') {
        if (this.stockManagerList.length > 0) {
          this.$refs.hospitalPhone.forEach(item => {
            if (item.getData()) {
              hospitalPhoneList.push(item.getData())
            } else {
              hospitalPhoneList.push('')
            }
          })
        }
        for (let i = 0; i < hospitalPhoneList.length; i++) {
          if (!hospitalPhoneList[i]) {
            this.$message.error('医院仓库管理员电话不能为空')
            return
          }
        }
      }
      if (hospitalPhoneList.length > 0 && this.stockManagerList.length == hospitalPhoneList.length) {
        data.adminPhone = hospitalPhoneList.toString()
      }
      if (this.hospitalSelfLocation.imgs.length == 0) {
        delete data.imgs
      } else if (this.hospitalSelfLocation.imgs.length > 0) {
        data.imgs = data.imgs.map(item => {
          return item.imgUrl
        }).toString()
      }
      if (!data.startHour) {
        delete data.startHour
      }
      if (!data.endHour) {
        delete data.endHour
      }
      if (!data.remark) {
        delete data.remark
      }
      if (data.hpFlag == '1' && data.inventoryFlag == '1') {
        delete data.hospitalSelfLocationEquList
        delete data.adminPhone
      }
      return data
    }
  }
}
</script>

<style lang="scss" scoped>
.hospitalPosition {
  ::v-deep .hide {
    .el-upload--picture-card {
      display: none !important;
    }
  }
}
</style>
